package com.qf.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.qf.pojo.Books;
import com.qf.service.IBooksService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
@Service
public class BooksServiceImpl implements IBooksService {

    private IBooksService booksService;
    private EurekaClient eurekaClient;
    private ObjectMapper objectMapper;

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    public void setEurekaClient(EurekaClient eurekaClient) {
        this.eurekaClient = eurekaClient;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setBooksService(IBooksService booksService) {
        this.booksService = booksService;
    }

    @Override
    public List<Books> findAll() throws JsonProcessingException {

//        参数1  服务器的名字
//        参数2 是不是https 请求
//        通过eureka 客户端从服务端中获取一个指定名字的服务器信息
/*        InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("04REDISCACHEPROVIDER-EUREKA", false);
//      获取到提供者的地址
        String homePageUrl = instanceInfo.getHomePageUrl();
        System.err.println("服务器的 dizhi shi ====>:"+homePageUrl);
//        查询 缓存*/
        String result = restTemplate.getForObject(  "http://04REDISCACHEPROVIDER-EUREKA/cache/get/alls", String.class);
//      缓存中没有数据则查询 数据库   并且存入到缓存
        if(result==null){
            System.out.println("来查是数据库了");
            List<Books> all = booksService.findAll();
            restTemplate.postForObject("http://04REDISCACHEPROVIDER-EUREKA/cache/set/alls", all, String.class);
            return all;
        }

        System.out.println("差的是缓存");
//        缓存中有数据
//        objectMapper.readValue(result, new TypeReference<List<Books>>(){
//
//        })
        //        缓存中有  将缓存中的JSON数据转换成 对象
        List<Books> booksList = objectMapper.readValue(result, new TypeReference<List<Books>>() {
        });
        return booksList;
    }
}
